<script setup lang="ts">
import {reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import axios from "axios";
import type {PageInfo} from "@/types/cg/Util.ts";
import {deleteItem} from "@/Api/CGApi/CGServ.ts";
import TestPage from "@/test/TestPage.vue";
import {ElMessage} from "element-plus";
import request from "@/util/request.ts";

let pageNum = ref(1)
let pageSize = ref(8)
let pageInfo = ref<PageInfo>({
  pages:0,
  pageNum:pageNum.value,
  pageSize:pageSize.value,
  total:0,
  list:null,
})
let allPage=ref(0)

const route = useRoute()
const router = useRouter()

let currentUser = reactive({
  uid:"1",
  userName:"admin",
})

const tableColumns = ref([
  { prop: 'id', label: '序号'  },
  { prop: 'code', label: '采购询价编码' , width:200 },
  { prop: 'uid', label: '采购员' },
  { prop: 'info', label: '备注' },
  { prop: 'status', label: '状态' },
  { prop: "total" , label: '参考金额'},
  { prop: "total_num" , label: '总数量'},
  { prop: 'get_date',label: '需求日期' ,width: 150},
  { prop: 'create_date', label: '制表日期' ,width: 150},
  { prop: 'createName' , label: '制表人' ,width: 150},
  { prop: 'modi_date' , label: '修改日期',width: 150},
  { prop: 'modi_id' ,label:'修改人' ,width: 150},
])


let tableData = ref<[]>([])
async function getPage(){
  let res = await request.post("cg/CGXJ/getPage",{
    "pageNum":pageNum.value,
    "pageSize":pageSize.value,
  })
  console.log(res.data.data)
  pageInfo = ref(res.data.data)
  tableData.value = pageInfo.value.list
  tableData.value.forEach(item =>{
    item.createName = "admin"
  })
  // pageNow.value = pageInfo.value.pageNum
  console.log(tableData.value);
  allPage.value = pageInfo.value.total
}
const handlePageChange = (newPage: number) => {
  pageNum.value = newPage
  getPage()
}

getPage()

const goModi=(code:any)=>{
  console.log(code.code)
  router.push({
    path:'cgxjInfo',
    query:{
      code: code.code // 传递单据编号
    }
  })
}
async function del(code:any){
  console.log(code.code)
  let res = await deleteItem(code , "CGXJ/delCGXJ")
  if (res.data.code == 200){
    pageNum.value = 1;
    await getPage();
  }
}
const fileInput = ref<HTMLInputElement | null>(null); // 文件输入框引用
const handleTableAction = (actionName: string,selectedRows?: any[]) => {
  if (actionName == "add"){
    router.push("cgxjInfo")
  }
  if (actionName == 'import') {
    fileInput.value?.click(); // 触发文件选择
  }
  if (actionName == 'export') {
    handleExport(selectedRows); // 触发导出
  }
  if (actionName === 'downLoadTemplate') {
    handleDownloadTemplate();
  }
}

const auditFormRef = ref();
const auditForm = reactive({
  code: '',
  checkManId: '',
  checkManName:'',
  checkComment: '',
  checkRes: null
});
// 表单验证规则
const auditRules = reactive({
  checkComment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
  checkRes: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});

let auditDialogVisible = ref(false)
const audit = (code:any)=>{
  auditForm.code = code.code
  auditForm.checkManName = currentUser.userName
  auditDialogVisible.value = true
}

const submitAudit = async () => {
  // 表单验证
  if (!await auditFormRef.value?.validate()) return;


  try {
    const response = await request.post('cg/CGXJ/check', {
      code: auditForm.code,
      typeId: 18,
      status: 3,
      checkManId: currentUser.uid.toString(),  // 绑定审核人ID
      checkComment: auditForm.checkComment, // 绑定审批意见
      checkRes: auditForm.checkRes // 绑定审核结果
    });

    ElMessage.success(response.data.message);
    auditDialogVisible.value = false;
    await getPage()
  } catch (error) {
    ElMessage.error('审核提交失败');
  } finally {
    // 重置表单
    auditForm.checkManId = '';
    auditForm.checkComment = '';
  }
};


const handleFileSelect = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];
  if (!file) {
    ElMessage.warning('未选择文件');
    return;
  }

  // 校验文件后缀
  const allowedExtensions = ['.xlsx', '.xls'];
  const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  if (!allowedExtensions.includes(fileExtension)) {
    ElMessage.error('文件格式不正确，仅支持 .xlsx 和 .xls 文件');
    input.value = ''; // 重置文件输入框
    return;
  }

  // 校验文件大小
  const maxFileSize = 10 * 1024 * 1024; //10MB
  if (file.size > maxFileSize) {
    ElMessage.error(`文件大小超过限制，最大允许10MB，当前文件大小'${file.size.toFixed(2)}MB'`);
    input.value = ''; //重置
    return;
  }

  const formData = new FormData();
  formData.append('file', file);

  // const loading = ElLoading.service({text: '正在导入...'});
  try {
    const response = await request.post('cg/CGXJ/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log(response.data.msg, ",", response.data.code)
    if (response.data.code == '200') {
      ElMessage.success('导入成功');
      pageNum.value = 1
      await getPage(); // 刷新表格数据
    } else {
      ElMessage.error(response.data.msg || "导入失败！");
    }
  } catch (error) {
    ElMessage.error('导入失败，请稍后重试');
    console.log(error)
  } finally {
    // loading.close();
    input.value = ''; // 重置文件输入框
  }
}

const handleExport = async (selectedRows?: any[]) => {

  // 过滤掉前端添加的额外字段
  const filteredRows = selectedRows ? selectedRows.map(row => {
    const {index, code_date,modi_date,get_date,create_date,createName, order_creation_time, modify_time, ...rest} = row;
    return rest;
  }) : [];
  console.log('过滤后的 filteredRows:', filteredRows);
  const params = {
    // pageNo: 1,
    // pageSize: pageSize.value,
    // code: queryConditions.code,
    // customerId: queryConditions.customerId,
    // invoiceNum: queryConditions.invoiceNum,
    selectedRows: filteredRows || [] // 包含选中行
    // name: queryConditions.name,
    // phoneNum: queryConditions.phoneNum,
  };
  // const loading = ElLoading.service({text: "正在导出..."});
  try {
    const response = await request.post("cg/CGXJ/export", params, {
      responseType: "blob",
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "采购发票信息表.xlsx");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请稍后重试");
  } finally {
    // loading.close();
  }
};

//下载模板
const handleDownloadTemplate = async () => {
  try {
    const response = await axios.get('cg/CGXJ/template', {
      responseType: 'blob',
    });
    console.log(response)
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '采购询价导入表.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('模板下载成功');
  } catch (error) {
    ElMessage.error('模板下载失败，请稍后重试');
  }
}

</script>

<template>

  <TestPage
      :table-data="tableData"
      :columns="tableColumns"
      :current-page="pageNum"
      :total="allPage"
      :page-size="pageSize"
      @page-change="handlePageChange"
      @action="handleTableAction"
      @edit="goModi"
      @audit="audit"
      @delete="del"
      @code-click="goModi"
  ></TestPage>

  <el-dialog
      v-model="auditDialogVisible"
      title="单据审核"
      width="600px"
      :close-on-click-modal="false"
  >
    <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
      <el-form-item label="单据编号：" prop="docCode">
        <el-input
            v-model="auditForm.code"
            disabled
            placeholder="系统自动填充"
        />
      </el-form-item>

      <el-form-item label="审核人：" prop="auditor">
        <el-input
            v-model="auditForm.checkManName"
            disabled
            placeholder="系统自动填充"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="审批意见：" prop="comment">
        <el-input
            v-model="auditForm.checkComment"
            type="textarea"
            :rows="3"
            placeholder="请输入审批意见"
            maxlength="200"
            show-word-limit
        />
      </el-form-item>
      <el-form-item label="审核结果：" prop="checkResult">
        <el-select
            v-model="auditForm.checkRes"
            placeholder="请选择审核结果"
            style="width: 100%"
        >
          <el-option label="通过" :value="true" />
          <el-option label="不通过" :value="false" />
        </el-select>
      </el-form-item>

    </el-form>

    <template #footer>
      <el-button @click="auditDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitAudit()">提交审核</el-button>
    </template>
  </el-dialog>
  <input
      type="file"
      ref="fileInput"
      style="display: none"
      accept=".xlsx,.xls"
      @change="handleFileSelect"
  />
</template>

<style scoped>

</style>
